<template>
  <div>
    <el-container>
      <el-header class="titleBar" height="100px">
        新闻管理
        <template>
          <el-tabs v-model="activeName" @tab-click="handleClick" class="tabs">
            <!-- 文章管理tabs -->
            <el-tab-pane label="文章管理" name="first">
              <el-main class="mainContent">
                <el-card style="margin-bottom:5px">
                  <!-- input框输入列 -->
                  <el-row :gutter="10">
                    <el-col :span="8">
                      <!-- 产品名称 -->
                      <div class="input_title_box">
                        <b class="input_title">新闻标题：</b>
                        <el-input
                          placeholder="请输入"
                          style="width:200px"
                          v-model="text"
                        ></el-input>
                      </div>
                    </el-col>
                    <el-col :span="14">
                      <div class="input_title_box">
                        <b class="input_title">发布时间：</b>
                        <el-date-picker
                          v-model="start"
                          type="date"
                          placeholder="选择开始日期"
                          style="width:200px"
                          value-format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                        <span style="padding:0 10px">-</span>
                        <el-date-picker
                          v-model="end"
                          type="date"
                          placeholder="选择结束日期"
                          style="width:200px"
                          value-format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                      </div>
                    </el-col>
                  </el-row>
                  <!-- 按钮操作列表 -->
                  <el-row :gutter="10">
                    <el-col :span="18"><div class="box_title"></div></el-col>
                    <el-col :span="5" style="margin-bottom:-20px">
                      <el-row :gutter="10">
                        <el-col :span="8"
                          ><el-button size="mini" @click="empty"
                            >重置</el-button
                          ></el-col
                        >
                        <el-col :span="8">
                          <el-button type="primary" size="mini" @click="search"
                            >查询</el-button
                          ></el-col
                        >
                        <el-col :span="6">
                          <el-button
                            type="success"
                            size="mini"
                            @click="addDialogVisible = true"
                            ><i class="el-icon-circle-plus-outline"></i>
                            添加</el-button
                          ></el-col
                        >
                      </el-row>
                    </el-col>
                  </el-row>
                </el-card>

                <el-card>
                  <!-- 表单数据 -->
                  <el-table
                    :data="newlist"
                    border
                    style="width: 100%"
                    :header-cell-style="{
                      textAlign: 'center',
                      background: '#ededed',
                      color: '#333',
                      fontWeight: '500',
                    }"
                    :cell-style="{ textAlign: 'center' }"
                  >
                    <el-table-column
                      label="新闻编号"
                      prop="id"
                    ></el-table-column>
                    <el-table-column label="新闻图片" prop="image">
                      <template slot-scope="scope">
                        <el-image
                          :src="scope.row.image"
                          style="width:40px;height:40px"
                          fit="cover"
                        ></el-image>
                      </template>
                    </el-table-column>
                    <el-table-column label="封面管理" prop="cover">
                      <template slot-scope="scope">
                        <el-image
                          :src="scope.row.cover"
                          style="width:40px;height:40px"
                          fit="cover"
                        ></el-image>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="新闻标题"
                      prop="title"
                    ></el-table-column>
                    <el-table-column
                      label="发布时间"
                      prop="pubdate"
                    ></el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-row :gutter="20" class="opBtn">
                          <el-col :span="10" class="etBtn">
                            <el-button
                              type="text"
                              @click="showEditDialog(scope.row)"
                              size="small"
                              >编辑</el-button
                            >
                          </el-col>
                          <el-col :span="10">
                            <el-button
                              type="text"
                              size="small"
                              class="deleteBtn"
                              @click="removeId(scope.row)"
                              >删除</el-button
                            >
                          </el-col>
                        </el-row>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!-- 分页 -->
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pagination.pagenum"
                    :page-sizes="[3, 5, 10, 15]"
                    :page-size="pagination.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total"
                  >
                  </el-pagination>
                </el-card>
              </el-main>
            </el-tab-pane>

            <!-- 封面管理 -->
          </el-tabs>
        </template>
      </el-header>
    </el-container>
    <!--  -->
    <el-dialog
      title="添加新闻"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item prop="file">
              <p>新闻图片：</p>
              <el-upload
                class="avatar-uploader"
                ref="upload"
                action="#"
                :data="addForm"
                :show-file-list="false"
                :multiple="false"
                :auto-upload="false"
                :on-change="imgSaveToUrl"
              >
                <img
                  v-if="this.addForm.image"
                  :src="this.addForm.image"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>          
          </el-col>
          <el-col :span="6">
             <el-form-item prop="file">
              <p>封面管理：</p>
              <el-upload
                class="avatar-uploader"
                ref="upload"
                action="#"
                :data="addForm"
                :show-file-list="false"
                :multiple="false"
                :auto-upload="false"
                :on-change="imgSaveToUrl1"
              >
                <img
                  v-if="this.addForm.cover"
                  :src="this.addForm.cover"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item>
              <p>新闻标题：</p>
              <el-input v-model="addForm.title" type="text"></el-input>
            </el-form-item>
            <el-form-item>
              <p>新闻内容：</p>
              <el-input v-model="addForm.content" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="编辑新闻"
      :visible.sync="editDialogVisible"
      width="70%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        @close="editDialogClosed"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item prop="file">
              <p>图片：</p>
              <el-upload
                class="avatar-uploader"
                ref="upload"
                action="#"
                :data="editForm"
                :show-file-list="false"
                :multiple="false"
                :auto-upload="false"
                :on-change="imgSaveToUrl"
              >
                <img
                  v-if="this.editForm.image"
                  :src="this.editForm.image"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="file">
              <p>轮播图片：</p>
              <el-upload
                class="avatar-uploader"
                ref="upload"
                action="#"
                :data="editForm"
                :show-file-list="false"
                :multiple="false"
                :auto-upload="false"
                :on-change="imgSaveToUrl1"
              >
                <img
                  v-if="this.editForm.cover"
                  :src="this.editForm.cover"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="title">
              <p>服务名称：</p>
              <el-input v-model="editForm.title" type="text"></el-input>
            </el-form-item>
            <el-form-item prop="content">
              <p>服务介绍</p>
              <el-input type="textarea" v-model="editForm.content"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editChartInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // select死数据
      options: [
        {
          value: "选项1",
          label: "尾板",
        },
        {
          value: "选项2",
          label: "车厢",
        },
      ],
      value: "",
      //
      activeName: "first",
      dialogVisible: false,
      // datepicker日期选择器
      start: "",
      end: "",
      text: "",
      // upload
      image: "",
      // 新闻数据展示
      newInfo: {
        total: 5,
        list: "",
      },
      pagination: {
        pagenum: 1,
        pagesize: 5,
        total: 7,
      },
      newlist: [],
      addDialogVisible: false,
      addForm: {
        id: "",
        image: "",
        content: "",
        cover: "",
        title: "",
      },
      file: "",
      addFormRules: {
        title: [{ required: true, message: "请输入文本", trigger: "blur" }],
      },
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 查询用户信息对象
      editForm: {
        content: "",
        image: "",
        title: "",
      },
      // 修改表单的校验规则对象
      editFormRules: {
        title: [{ required: true, message: "请输入文本", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //图片上传
    async imgSaveToUrl(event) {
      if (this.beforeUploadPicture(event.raw)) {
        var formData = new FormData();
        formData.append("file", event.raw);
        this.http.upload("/news/upload", formData).then((res) => {
          if (res.code == 200) {
            this.addForm.image = res.data;
            // this.addForm.cover = res.data;
            this.editForm.image = res.data;
            // this.editForm.cover = res.data;
            console.log(res.data);
            console.log(this.addForm);
            this.$message.success("上传成功");
          }
        });
      }
    },
    async imgSaveToUrl1(event) {
      if (this.beforeUploadPicture(event.raw)) {
        var formData = new FormData();
        formData.append("file", event.raw);
        this.http.upload("/news/upload", formData).then((res) => {
          if (res.code == 200) {
            // this.addForm.image = res.data;
            this.addForm.cover = res.data;
            // this.editForm.image = res.data;
            this.editForm.cover = res.data;
            console.log(res.data);
            console.log(this.addForm);
            this.$message.success("上传成功");
          }
        });
      }
    },
    // 图片上传之前
    beforeUploadPicture(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
      }
      if (isJPG && isPNG) {
        if (!isLt10M) {
          this.$message.error("上传头像图片大小不能超过 10MB!");
        }
      }

      return (isJPG || isPNG) && isLt10M;
    },
    // 后台数据展示
    async getNewList() {
      const res = await this.http.get("/news/select", this.pagination);
      this.newlist = res.list;
      this.pagination.total = res.total;
    },
    //  监听pagesize的改变
    handleSizeChange(newSize) {
      this.pagination.pagesize = newSize;
      this.getNewList();
    },
    handleCurrentChange(newPage) {
      this.pagination.pagenum = newPage;
      this.getNewList();
    },
    // 添加
    // 添加轮播图
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    onSubmit() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        //  发送网路请求
        const { res } = await this.http.post("/news/add", this.addForm);
        console.log(res);

        if (status.code !== 200) {
          this.$message.error("添加行为失败");
        }
        this.$message.success("添加行为成功！");
        this.addDialogVisible = false;
        this.getNewList();
      });
    },
    // 查询
    async search() {
      const res = await this.http.get("/news/selectVague", {
        end: this.end,
        start: this.start,
        pagenum: this.pagination.pagenum,
        pagesize: this.pagination.pagesize,
        title: this.text,
      });
      console.log(res);
      this.newlist = res.list;
      this.pagination.total = res.total;
    },
    // 编辑
    async showEditDialog(row) {
      this.editForm = row;
      const res = await this.http.post("/news/update", row);

      this.editDialogVisible = true;
      console.log(row);
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户信息并提交
    editChartInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        // 发起请求获取
        const res = await this.http.post("/news/update", this.editForm, {
          title: this.editForm.title,
          content: this.editForm.content,
          image: this.editForm.image,
        });

        if (status.code !== 200) {
          this.$message.error("编辑服务失败！");
        }
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据
        this.getNewList();
        // 提示修改成功
        this.$message.success("编辑失败成功!");
        console.log(res);
      });
    },
    // 删除
    async removeId(row) {
      console.log(row);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const res = await this.http.post("/news/delete", row.id);
      console.log(res);
      this.getNewList();
    },
    empty() {
      this.text = "";
      this.end = "";
      this.start = "";
    },
  },
  created() {
    this.getNewList();
  },
};
</script>

<style scoped>
.header_title {
  font-size: 22px;
  margin-bottom: 0px;
  font-weight: 400;
  color: #999999;
}
.bgk {
  background: pink;
}
.avatar-uploader-icon {
  /* border: 2px dashed #dedede; */
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}
/deep/ .el-textarea__inner {
  line-height: 3 !important;
}
</style>
